package exampleQuestions;

public class PrintASpiralMatrix {

	/**
	 * Print an array in a spiral manner
	 * 
	 * given a number n... print a spiral matrix in O(1) space example if n=5
	 * the op should be: 25 24 23 22 21 10 09 08 07 20 11 02 01 06 19 12 03 04
	 * 05 18 13 14 15 16 17 The question may appear trivial but its not...u hav
	 * to print in O(1) space
	 */
	public static void main(String[] args) {

		int[][] array = { { 25, 24, 23, 22, 21 }, { 10, 9, 8, 7, 20 },
				{ 11, 2, 1, 6, 19 }, { 12, 3, 4, 5, 18 },
				{ 13, 14, 15, 16, 17 } };

		printMatrix(array);

	}

	private static void printMatrix(int[][] array) {

		for (int i = 0; i < array.length / 2; i++) {
			printSquare(i, array.length - i - 1, array);
		}

		if (array.length % 2 == 1) {
			System.out.print(array[array.length / 2 ][array.length / 2]);
		}
	}

	private static void printSquare(int i, int j, int[][] array) {
		// x axis
		for (int k = i; k <= j; k++) {
			System.out.print(array[i][k] + " ");
		}

		// y axis
		for (int k = i + 1; k <= j; k++) {
			System.out.print(array[k][j] + " ");
		}

		// x axis
		for (int k = j - 1; k >= i; k--) {
			System.out.print(array[j][k] + " ");
		}

		// y axis
		for (int k = j - 1; k > i; k--) {
			System.out.print(array[k][i] + " ");
		}

	}

}
